﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Drawing;

using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;

using Leadtools;
using Leadtools.Codecs;
using Leadtools.WinForms;


using FastReport;
using FastReport.Preview;

using MINERP.BLL.CustomerManage;
using System.Data;
using MINERP.COM;
using MINERP.MODEL.FoundationModel;
using MINERP.BLL.Common;
using MINERP.ComControls;
using System.Threading;



namespace MINERP.CustomerManage.Controller
{
    public class OrderBagController : ControllerBase
    {
        #region //private fields

        /// <summary>
        /// 业务操作
        /// </summary>
        internal OrderBagManageBLL _bll = new OrderBagManageBLL();
        PrinterBill pbill = new PrinterBill();
        /// <summary>
        /// 订单包的显示控件
        /// </summary>
        private GridControl _grid = null;
        /// <summary>
        /// 单个订单包详细信息的现实
        /// </summary>
        private GridControl _gridCard = null;
        /// <summary>
        /// 产品停止、恢复信息记录
        /// </summary>
        private GridControl _gridStopRecord = null;
        /// <summary>
        /// 按订单状态进行筛选
        /// </summary>
        private ToolStripComboBox _cmbStatus = null;
        /// <summary>
        /// 订单包的显示界面
        /// </summary>
        private GridView _view = null;
        /// <summary>
        /// 订单包内部其中一张图片
        /// </summary>
        private RasterImageViewer _imageViewer = null;
        /// <summary>
        /// 为了实现在卡片中显示的绑定对象
        /// </summary>
        private List<OrderBagEntity> _listOrderBag = new List<OrderBagEntity>();
        /// <summary>
        /// 当前行对象
        /// </summary>
        private OrderBagEntity _focusObj = null;

        private List<string> _codeList = null;

        private List<string> _orderNameList = null;


        /// <summary>
        /// 当前的记录数
        /// </summary>
        private List<OrderBagEntity> _currentList = new List<OrderBagEntity>();
        /// <summary>
        /// 判断当前的显示是否是查询的结果
        /// </summary>
        private bool _isSearchedResult = false;

        private Report report = new Report();



        #endregion

        #region //public Priorities

        internal GridControl Grid
        {
            set
            {
                this._grid = value;
            }
        }

        internal GridControl GridCard
        {
            set
            {
                this._gridCard = value;
            }
        }

        internal GridControl GridStopRecord
        {
            get { return _gridStopRecord; }
            set { _gridStopRecord = value; }
        }

        internal GridView View
        {
            set
            {
                this._view = value;
            }
        }

        internal ToolStripComboBox CmbStatus
        {
            set
            {
                this._cmbStatus = value;
            }
            get
            {
                return this._cmbStatus;
            }
        }

        internal RasterImageViewer ImageViewer
        {
            set
            {
                this._imageViewer = value;
            }
        }

        //当前订单集合的订单条码集合
        internal List<string> CoedList
        {
            get;
            set;
        }
        //当前订单集合的订单名称集合
        internal List<string> OrderNameList
        {
            get;
            set;
        }


        /// <summary>
        /// 设置查询的结果
        /// </summary>
        internal List<OrderBagEntity> ResultList
        {
            set
            {
                this._currentList = value;
            }
        }

        /// <summary>
        /// 得到订单的数量
        /// </summary>
        internal int OrderBagCount
        {

            //get
            //{
            //    //如果是查询就计算查询结果的数量
            //    if (this._isSearchedResult)
            //    {
            //        return this._currentList.Count;
            //    }

            //    return this._bll.GetOrderBagCount();
            //}
            get;
            set;
        }
        /// <summary>
        /// 得到订单下的所有产品
        /// </summary>
        internal int ProductCount
        {
            get;
            set;
        }

        /// <summary>
        /// 得到或设置是不是查询的结果
        /// </summary>
        internal bool IsSearchedResult
        {
            get
            {
                return this._isSearchedResult;
            }
            set
            {
                this._isSearchedResult = value;
            }
        }

        #endregion

        #region//public methods


        #region //get methods

        /// <summary>
        /// 初始化得数据
        /// </summary>
        internal void InitViewData(int status)
        {
            _currentList = _bll.GetRequestPageData(0, 50, status);
        }

        private int GetStatus()
        {
            string statusStr = this.CmbStatus.Text;
            int status = -1;
            switch (statusStr)
            {
                case "正常生产":
                    status = (int)COM.OrderBagStatus.Doing; break;
                case "生产完成":
                    status = (int)COM.OrderBagStatus.Completed; break;
                case "暂停生产":
                    status = (int)COM.OrderBagStatus.OrderBagStop; break;
                case "未生产":
                    status = (int)COM.OrderBagStatus.UnComplete; break;
                case "错误":
                    status = (int)COM.OrderBagStatus.Eroor; break;
                case "全部":
                    status = -1; break;
            }
            return status;
        }

        #region //分页功能

        /// <summary>
        /// 当分页的数量改变时自动调整当前显示返回总页数
        /// </summary>
        /// <param name="pageCount">每页数量</param>
        /// <param name="page">第几页</param>
        internal int PageCountChanged(int pageCount, int pageNumber, int status)
        {
            //没有记录存在
            if (OrderBagCount == 0)
            {
                _currentList.Clear();
                this._grid.DataSource = null;
                this._grid.RefreshDataSource();
                return 1;

            }
            int startIndex = 0;
            int totalPage = OrderBagCount % pageCount == 0 ? OrderBagCount / pageCount : (OrderBagCount / pageCount + 1);
            if (totalPage == 0)
                totalPage = 1;
            if (totalPage < pageNumber)
                pageNumber = totalPage;

            //如果是第一页
            if (pageNumber == 1)
            {
                startIndex = 0;
            }
            else
            {
                startIndex = (pageNumber - 1) * pageCount;
            }

            if (startIndex <= this.OrderBagCount)
            {
                int endIndex = startIndex + pageCount;

                if (endIndex > this.OrderBagCount)
                {
                    endIndex = this.OrderBagCount;
                }

                if (_currentList.Count > 0)
                {
                    _currentList.Clear();
                }

                if (status == (int)COM.OrderBagStatus.Completed)                            //已完成   
                {
                    _currentList = _bll.GetRequestPageData_bk(startIndex, endIndex);     //明天这里有问题
                }
                else
                {
                    _currentList = _bll.GetRequestPageData(startIndex, endIndex, status);
                }
                /*List<OrderBagEntity2> _xxx = new List<OrderBagEntity2>();
                foreach (OrderBagEntity obe in _currentList)
                {
                    OrderBagEntity2 obe2 = new OrderBagEntity2();
                    obe2.BagCode = obe.BagCode;
                    obe2.BagName = obe.BagName;
                    obe2.CompleteTime = obe.CompleteTime;
                    obe2.FetchTime = obe.FetchTime;
                    obe2.OrderBagID = obe.OrderBagID;
                    obe2.OrderTime = obe.OrderTime;
                    obe2.PreCompleteTime = obe.PreCompleteTime;
                    obe2.Priority = obe.Priority;
                    obe2.Remark = obe.Remark;
                    obe2.ShopName = obe.ShopName;
                    _xxx.Add(obe2);
                }*/
                this._grid.DataSource = _currentList;
                this._grid.RefreshDataSource();

                return pageNumber;
            }
            else
            {
                this._grid.DataSource = null;
                this._grid.RefreshDataSource();

                return 1;
            }
        }

        #region//查询结果的分页处理

        internal int SearchResultPageChanged(int pageCount, int pageNumber)
        {
            int startIndex = 0;
            int totalPage = OrderBagCount % pageCount == 0 ? OrderBagCount / pageCount : (OrderBagCount / pageCount + 1);
            if (totalPage == 0)
                totalPage = 1;
            if (totalPage < pageNumber)
                pageNumber = totalPage;

            //如果是第一页
            if (pageNumber == 1)
            {
                startIndex = 0;
            }
            else
            {
                startIndex = (pageNumber - 1) * pageCount;
            }

            if (startIndex <= this.OrderBagCount)
            {
                int endIndex = startIndex + pageCount;

                if (endIndex > this.OrderBagCount)
                {
                    endIndex = this.OrderBagCount;
                }

                List<OrderBagEntity> tempList = new List<OrderBagEntity>();

                for (int i = startIndex; i < endIndex; i++)
                {
                    tempList.Add(_currentList[i]);
                }

                this._grid.DataSource = tempList;
                this._grid.RefreshDataSource();

                return pageNumber;
            }
            else
            {
                this._grid.DataSource = null;
                this._grid.RefreshDataSource();

                return 1;
            }
        }

        /// <summary>
        /// 获取指定状态下订单总量,产品总量
        /// </summary>
        /// <param name="status"></param>
        public void GetTotalOrderNum(int status)
        {
            if (status == (int)COM.OrderBagStatus.Completed)
            {
                OrderBagCount = this._bll.GetOrderBagCount_bk();
                ProductCount = this._bll.GetOrderInfoCount_bk();
            }
            else
            {
                OrderBagCount = this._bll.GetOrderBagCount(status);
                ProductCount = this._bll.GetOrderInfoCount(status);
            }
        }

        /// <summary>
        /// 获取查询状态下订单总量，产品总量
        /// </summary>
        public void GetTotalOrderNum()
        {
            int orderNum = 0;
            int productNum = 0;
            _bll.GetTotalOrderNum(out orderNum, out productNum);
            OrderBagCount = orderNum;
            ProductCount = productNum;
        }

        /// <summary>
        /// 设置快速筛选的订单编号和订单名称
        /// </summary>
        public void SetFastSelectOrderCodeAndOrderName()
        {
            CoedList = _bll.GetShowOrderCode();
            OrderNameList = _bll.GetShowOrderName();
        }

        #endregion

        #endregion

        /// <summary>
        /// 绑定选中的对象到CARDVIEW中显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void GetOrderBagDetail(object sender, int rowIndex)
        {
            GridView view = (GridView)sender;

            if (_listOrderBag.Count > 0)
                _listOrderBag.Clear();

            OrderBagEntity obj = (OrderBagEntity)view.GetRow(rowIndex);
            _listOrderBag.Add(obj);

            SetOrderBagDetail(_listOrderBag);
        }

        public void SetOrderBagDetail(List<OrderBagEntity> listOrder)
        {
            _gridCard.DataSource = listOrder;
            _gridCard.RefreshDataSource();
        }

        #endregion

        #region //Rapid Search Function
        /// <summary>
        /// 快速筛选的方法
        /// </summary>
        /// <param name="condition"></param>
        internal void RapidSearch(RapidCondition condition)
        {
            if (this._isSearchedResult)
            {
                this._currentList = _bll.RapidSearch(condition);
            }
            else
            {
                this._currentList = _bll.RapidSearch(condition);
                this._grid.DataSource = _currentList;
                this._grid.RefreshDataSource();
            }
        }

        #endregion

        #region //update methods

        internal void Update(int priority)
        {
            this._focusObj = (OrderBagEntity)this._view.GetFocusedRow();
            this._focusObj.Priority = priority;

            //try
            //{
            //    if (this._focusObj.IsDirty)
            //    {
            //        this._focusObj.IsDirty = false;
            //        _bll.Update();
            //        MessageBox.Show("更改成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);

            //    return;
            //}

        }

        internal void Update(DateTime date)
        {
            this._focusObj = (OrderBagEntity)this._view.GetFocusedRow();
            this._focusObj.FetchTime = date;

            //try
            //{
            //    if (this._focusObj.IsDirty)
            //    {
            //        this._focusObj.IsDirty = false;
            //        _bll.Update();
            //        MessageBox.Show("更改成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);

            //    return;
            //}
        }

        /// <summary>
        /// 更新要编辑的行为正在编辑状态
        /// </summary>
        internal void UpdateEditStatus()
        {
            _bll.Update();
        }

        #endregion


        #region //Check Methods

        /// <summary>
        /// 检查用户要编辑的行是否为可编辑状态
        /// </summary>
        /// <returns></returns>
        internal bool CheckUsed()
        {
            this._focusObj = (OrderBagEntity)this._view.GetFocusedRow();

            if (this._focusObj != null)
            {
                if (this._focusObj.IsEdit != 0)
                {
                    MessageBox.Show("你选中的行别人正在编辑中，请稍后再试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    return false;
                }
            }

            return true;
        }

        #endregion

        internal void Exit(FormClosingEventArgs e)
        {
            if (MessageBox.Show("确定退出系统？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                Application.Exit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 更新订单的生产状态
        /// </summary>
        internal void UpdateProductStatus()
        {
            _bll.Update();
        }

        /// <summary>
        /// 更新订单与其所有的产品状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="status"></param>
        public void UpdateOrderAndOrderInfoStatus(int orderId, int orderStatus, int productStatus)
        {
            _bll.UpdateOrderAndOrderInfoStatus(orderId, orderStatus, productStatus);
        }

        /// <summary>
        /// 单独修改订单的状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="orderStatus"></param>
        public void UpdateOrderStatus(int orderId, int orderStatus)
        {
            _bll.UpdateOrderStatus(orderId, orderStatus);
        }


        #region //订单超时报警

        internal void CheckAlarm(RowStyleEventArgs e)
        {
            if (this._view != null)
            {
                OrderBagEntity item = this._view.GetRow(e.RowHandle) as OrderBagEntity;

                if (item != null)
                {
                    if (item.StatusValue == (int)OrderBagStatus.Completed)
                    {
                        e.Appearance.BackColor = Color.Empty;
                        e.Appearance.BackColor2 = Color.Empty;
                        return;
                    }
                    if (item.StatusValue == (int)OrderBagStatus.OrderBagStop)
                    {
                        e.Appearance.BackColor = Color.LightSlateGray;
                        e.Appearance.BackColor2 = Color.LightSlateGray;

                        return;
                    }

                    if (item.StatusValue == (int)OrderBagStatus.ProductStop)
                    {
                        e.Appearance.BackColor = Color.GreenYellow;
                        e.Appearance.BackColor2 = Color.GreenYellow;

                        return;
                    }

                    if (item.FetchTime <= DateTime.Now.AddHours(Properties.Settings.Default.AlarmTime))
                    {
                        e.Appearance.BackColor = Color.LightPink;
                        e.Appearance.BackColor2 = Color.LightPink;
                    }
                }
            }
        }

        #endregion

        #region//报表功能

        /// <summary>
        /// 填充报表的数据源
        /// </summary>
        internal DataSet FillReportData()
        {
            this._focusObj = (OrderBagEntity)this._view.GetFocusedRow();
            DataTable dtOrderBag = new DataTable();

            dtOrderBag.TableName = "OrderBag";

            //主表
            DataColumn BagCode = dtOrderBag.Columns.Add("BagCode");
            DataColumn BagName = dtOrderBag.Columns.Add("BagName");
            DataColumn ShopName = dtOrderBag.Columns.Add("ShopName");
            DataColumn OrderTime = dtOrderBag.Columns.Add("OrderTime");
            DataColumn CompleteTime = dtOrderBag.Columns.Add("CompleteTime");
            DataColumn FetchTime = dtOrderBag.Columns.Add("FetchTime");
            DataColumn Status = dtOrderBag.Columns.Add("Status");
            DataColumn Priority = dtOrderBag.Columns.Add("Priority");
            DataColumn Remark = dtOrderBag.Columns.Add("Remark");
            DataColumn UserName = dtOrderBag.Columns.Add("UserName");

            DataRow row = dtOrderBag.Rows.Add();

            row["BagCode"] = this._focusObj.BagCode;
            row["BagName"] = this._focusObj.BagName;
            row["ShopName"] = this._focusObj.ShopName;
            row["OrderTime"] = this._focusObj.OrderTime;
            if (this._focusObj.CompleteTime != null)
            {
                row["CompleteTime"] = this._focusObj.CompleteTime;
            }
            else
            {
                row["CompleteTime"] = "未完成";
            }
            row["FetchTime"] = this._focusObj.FetchTime;
            row["Status"] = this._focusObj.Status;
            row["Priority"] = this._focusObj.Priority;
            row["Remark"] = this._focusObj.Remark;
            row["UserName"] = this._focusObj.UserName;


            OrderInfoController infoController = new OrderInfoController();
            DataTable dtOrderInfo = infoController.FillSubData(this._focusObj.OrderBagID);

            dtOrderInfo.TableName = "OrderInfo";

            DataSet ds = new DataSet();

            ds.Tables.Add(dtOrderBag);

            ds.Tables.Add(dtOrderInfo);

            //ds.WriteXml(@"C:\Reprot.xml");
            ds.WriteXml(@"C:\windows\xmlData\Reprot.xml", XmlWriteMode.WriteSchema);

            return ds;

        }

        #endregion

        #region //HelperFunction
        /// <summary>
        /// 当点击到一个订单包时就显示出订单中的一张照片
        /// </summary>
        internal void GetDefaultBagImage()
        {
            OrderBagEntity obj = this._view.GetFocusedRow() as OrderBagEntity;

            string path = string.Empty;
            if (obj != null)
            {
                path = _bll.GetImagePathByBagID(obj.OrderBagID);
            }

            this._imageViewer.Image = null;
            if (path != string.Empty)
            {
                try
                {
                    RasterCodecs.Startup();
                    this._imageViewer.SizeMode = RasterPaintSizeMode.Normal;
                    this._imageViewer.Image = GetOneRasterImage(path);
                    this._imageViewer.Tag = path;
                    RasterCodecs.Shutdown();
                }
                catch
                {
                    try
                    {
                        RasterCodecs.Startup();
                        RasterCodecs codecs = new RasterCodecs();
                        RasterImage img = codecs.Load(path);
                        _imageViewer.SizeMode = RasterPaintSizeMode.FitAlways;
                        this._imageViewer.Image = new RasterImage(img);
                        this._imageViewer.Tag = path;
                        RasterCodecs.Shutdown();
                    }
                    catch
                    {
                        this._imageViewer.Image = new RasterImage(Image.FromFile(Application.StartupPath + "\\" + "PhotoNotFind.jpg"));
                        this._imageViewer.SizeMode = RasterPaintSizeMode.FitAlways;
                        this._imageViewer.Tag = Application.StartupPath + "\\" + "PhotoNotFind.jpg";
                        return;
                    }
                }
            }
        }

        /// <summary>
        /// 得到照片的缩略图
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private RasterImage GetOneRasterImage(string path)
        {
            RasterCodecs codecs = new RasterCodecs();
            CodecsThumbnailOptions options = new CodecsThumbnailOptions();
            options.Resample = true;
            options.LoadStamp = true;
            options.MaintainAspectRatio = true;

            RasterImage img = codecs.ReadThumbnail(path, options, 1);
            codecs.Dispose();

            return img;
        }

        #endregion

        #endregion

        /// <summary>
        /// 设置停止、恢复产品生产的数据源
        /// </summary>
        public void SetStopRecord(int productId)
        {
            List<StopRecord> stopRecordList = _bll.GetStopRecords(productId);
            _gridStopRecord.DataSource = stopRecordList;
            _gridStopRecord.RefreshDataSource();
        }

        /// <summary>
        /// 获取所有的流程节点，并缓存起来
        /// </summary>
        public void SetAllTechs()
        {
            _bll.SetAllTechs();
        }

        /// <summary>
        /// 获取当前订单的当前流程集合
        /// </summary>
        /// <returns></returns>
        public List<TechInfo> GetCurrentTechs()
        {
            return _bll.GetCurrentTechs();
        }

        /// <summary>
        /// 获取当前订单集合的加急级别集合
        /// </summary>
        /// <returns></returns>
        public List<int> GetCurrentPriority()
        {
            return _bll.GetCurrentPriority();
        }


        /// <summary>
        /// 更新指定订单的加急级别
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="priority"></param>
        public void UpdatePriority(int orderId, int priority)
        {
            try
            {
                _bll.UpdatePriority(orderId, priority);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

         ////<summary>
         ////插入停止还是恢复产品的备注(以订单为单位)
         ////</summary>
         ////<param name="status"></param>
        public void InsertStopOrRecorverRemark(int orderId, int status, string remark, int userId)
        {
            try
            {
                _bll.InsertStopOrRecorverRemark(orderId, status, remark, userId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 插入停止还是恢复产品的备注(以产品为单位)
        /// </summary>
        /// <param name="status"></param>
        public void InsertStopOrRecorverRemark2(int productId, int status, string remark, int userId)
        {
            try
            {
                _bll.InsertStopOrRecorverRemark2(productId, status, remark, userId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取指定产品的状态
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public int GetOrderInfoStatus(int productId)
        {
            try
            {
                return _bll.GetOrderInfoStatus(productId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 产品中是否有照片已经拼版
        /// </summary>
        /// <param name="orderproductId"></param>
        /// <returns></returns>
        public bool MakeBigBoardOK(int orderproductId)
        {
            return _bll.MakeBigBoardOK(orderproductId);
        }

        /// <summary>
        /// 删除垃圾订单
        /// </summary>
        /// <param name="userId"></param>
        public void DeleteTempOrder(int userId)
        {
            try
            {
                _bll.DeleteTempOrder(userId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取产品的当前节点
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public string GetProductTech(int productId)
        {
            try
            {
                return _bll.GetProductTech(productId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取指定产品的基本信息
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public MODEL.CustomerManage.CurrentStyleProduct GetStyleProduct(int productId, int orderStatus)
        {
            try
            {
                if (productId == 0)
                    return null;
                if (orderStatus == (int)COM.OrderBagStatus.Completed)
                {
                    return _bll.GetStyleProduct_bk(productId);
                }
                else
                {
                    return _bll.GetStyleProduct(productId);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 删除订单(将订单状态置为删除，不是真删)
        /// <summary>
        /// 删除订单(将订单状态置为删除，不是真删)
        /// </summary>
        /// <param name="orderBagId"></param>
        public int DeleteOrderBag(int orderBagId, int edituserId)
        {
            int rtnVal = 0;
            try
            {
                _bll.DeleteOrderBag(orderBagId, edituserId);
                rtnVal = 1;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rtnVal;
        }
        /// <summary>
        /// 删除订单(将订单状态置为删除，不是真删)
        /// </summary>
        /// <param name="orderBagId"></param>
        public int DeleteOrderBag(int orderBagId, int inOrderproductid, int editUserId)
        {
            int rtnVal = 0;
            try
            {
                _bll.DeleteOrderBag(orderBagId, inOrderproductid, editUserId);
                rtnVal = 1;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rtnVal;
        }
        #endregion

        /// <summary>
        /// 强制将产品从等待付款改变生产
        /// </summary>
        /// <param name="_focusOrderInfo"></param>
        /// <param name="_focusOrderBag"></param>
        internal void SetOrderToProduct(OrderInfoEntity _focusOrderInfo, OrderBagEntity _focusOrderBag)
        {
            if (_focusOrderInfo != null && _focusOrderBag != null)
            {
                _bll.SetOrderToProduct(_focusOrderInfo, _focusOrderBag);
            }
        }

        /// <summary>
        /// 得到产品的返单记录
        /// </summary>
        /// <param name="item"></param>
        internal DataTable GetReBackOrderReCord(OrderInfoEntity item)
        {
            if (item != null)
            {
                return _bll.GetReBackOrderReCord(item);
            }
            return null;
        }

        /// <summary>
        /// 现结类型打印收款单
        /// </summary>
        /// <param name="orderbagid"></param>
        internal void PrintTicket(int orderbagid, string userName, string shopName)
        {
            SHOP_Bill_Info sbInfo = _bll.GetShopBillInfo(orderbagid);
            if (sbInfo.List_Detail.Count > 0)
            {
                int billIndex = _bll.SaveTicketRecords(orderbagid, shopName, userName, (decimal)sbInfo.BillCount);
                PrintBill(sbInfo, billIndex);
            }
            else
            {
                MessageBox.Show("没有可打单的产品!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 现结类型打印收款单
        /// </summary>
        /// <param name="orderbagid"></param>
        internal void PrePrintBill(int orderbagid)
        {
            if (MessageBox.Show("是否分打账单，是 点击 ’确定‘,否 点击’取消‘", "确定", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                List<SHOP_Bill_Info> sbiList = PrintOrdersToBill.OrganizationBillDataList(orderbagid);
                foreach (SHOP_Bill_Info sbi in sbiList)
                {
                    DataSet set = pbill.PrintBill(sbi);
                    set.WriteXml(Application.StartupPath + @"\PrintShopBill.xml", XmlWriteMode.WriteSchema);
                    Report report = new Report();
                    report.Load(Application.StartupPath + "\\Report\\PrintShopBill.frx");
                    report.RegisterData(set.Tables["tableTitle"], "tableTitle");
                    report.RegisterData(set.Tables["tableDetail"], "tableDetail");
                    report.RegisterData(set.Tables["tableSubDetail"], "tableSubDetail");
                    //report.RegisterData(tableBottom, "tableBottom");
                    //设置合计参数

                    report.SetParameterValue("Para_TotalNum", set.Tables["tableTitle"].Rows[0]["Para_TotalNum"]);
                    report.SetParameterValue("Para_TotalAreas", set.Tables["tableTitle"].Rows[0]["Para_TotalAreas"]);
                    report.SetParameterValue("Para_TotalCount", set.Tables["tableTitle"].Rows[0]["Para_TotalCount"]);
                    report.SetParameterValue("Para_Sum", set.Tables["tableTitle"].Rows[0]["Para_Sum"]);
                    report.SetParameterValue("Para_TotalPrintCount", set.Tables["tableTitle"].Rows[0]["Para_TotalPrintCount"]);
                    report.SetParameterValue("Para_TotalProductCount", set.Tables["tableTitle"].Rows[0]["Para_TotalProductCount"]);
                    //report.Show();
                    report.PrintSettings.ShowDialog = false;
                    report.Print();
                   // Thread.Sleep(30000);
                }
                
            }
            else
            {
                SHOP_Bill_Info sbi = PrintOrdersToBill.OrganizationBillData(orderbagid);
                if (sbi.Result == -1)
                {
                    MessageBox.Show("没有可打单的产品!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;

                }
                if (sbi.Result == -2)
                {
                    MessageBox.Show("已经打过结账单!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                DataSet set = pbill.PrintBill(sbi);
                set.WriteXml(Application.StartupPath + @"\PrintShopBill.xml", XmlWriteMode.WriteSchema);
                Report report = new Report();
                report.Load(Application.StartupPath + "\\Report\\PrintShopBill.frx");
                report.RegisterData(set.Tables["tableTitle"], "tableTitle");
                report.RegisterData(set.Tables["tableDetail"], "tableDetail");
                report.RegisterData(set.Tables["tableSubDetail"], "tableSubDetail");
                //report.RegisterData(tableBottom, "tableBottom");
                //设置合计参数

                report.SetParameterValue("Para_TotalNum", set.Tables["tableTitle"].Rows[0]["Para_TotalNum"]);
                report.SetParameterValue("Para_TotalAreas", set.Tables["tableTitle"].Rows[0]["Para_TotalAreas"]);
                report.SetParameterValue("Para_TotalCount", set.Tables["tableTitle"].Rows[0]["Para_TotalCount"]);
                report.SetParameterValue("Para_Sum", set.Tables["tableTitle"].Rows[0]["Para_Sum"]);
                report.SetParameterValue("Para_TotalPrintCount", set.Tables["tableTitle"].Rows[0]["Para_TotalPrintCount"]);
                report.SetParameterValue("Para_TotalProductCount", set.Tables["tableTitle"].Rows[0]["Para_TotalProductCount"]);
                report.PrintSettings.ShowDialog = false;
                report.Print();
            }
        }

        /// <summary>
        /// 打印帐单
        /// </summary>
        /// <param name="sbinfo"></param>
        private void PrintBill(SHOP_Bill_Info sbinfo, int billIndex)
        {
            report.Load(Application.StartupPath + "\\Report\\PrintTicket.frx");

            #region//富士打印
            if (sbinfo.IsAssignByCustom)
            {

            }
            #endregion
            #region 组织打印数据

            bool IsNeedPrintMoney = sbinfo.Shop.IsNeedPrintUPrice;
            DataTable tableTitle = CreateShopBillTitle();
            DataRow titleRow = tableTitle.NewRow();
            titleRow["ShopName"] = sbinfo.Shop.ShopName;
            titleRow["Tel1"] = sbinfo.Shop.Tel1;
            titleRow["Tel2"] = sbinfo.Shop.Tel2;
            titleRow["ShopId"] = sbinfo.Shop.ShopId;
            titleRow["shopKeeper"] = sbinfo.Shop.ShopKeeper;
            titleRow["QQ"] = sbinfo.Shop.QQ;
            titleRow["BillId"] = sbinfo.BillId;
            titleRow["BillOrderCode"] = sbinfo.BillOrderCode;
            titleRow["CreateTime"] = sbinfo.CreateTime;
            titleRow["BillIndex"] = billIndex.ToString();
            titleRow["CheckOutType"] = sbinfo.CheckTypeString;
            if (IsNeedPrintMoney)
            {
                titleRow["Balance"] = sbinfo.ShopBalance;
                titleRow["BillCount"] = sbinfo.BillCount;
            }
            else
            {
                titleRow["Balance"] = 0;
                titleRow["BillCount"] = 0;
            }


            titleRow["Salesman"] = sbinfo.Salesman;
            titleRow["CreditLevel"] = sbinfo.CreditLevel == null ? 0 : sbinfo.CreditLevel;
            tableTitle.Rows.Add(titleRow);

            tableTitle.TableName = "tableTitle";


            DataTable tableDetail = CreateShopBillDetail();
            DataTable tableSubDetail = CreateShopBillSubDetail();
            List<Bill_Detail_Info> detailList = sbinfo.List_Detail.ToList();

            foreach (Bill_Detail_Info billDetail in detailList)
            {
                DataRow row = tableDetail.NewRow();
                row["BillDetailId"] = billDetail.BillDetailId;
                row["OrderInfoCode"] = billDetail.OrderInfoCode;
                row["OrderProductName"] = billDetail.OrderProductName;
                row["CtmName"] = billDetail.CtmName;
                row["Remark"] = billDetail.Remark;
                row["OrderBagName"] = billDetail.OrderBagName;

                tableDetail.Rows.Add(row);
                List<Bill_Detail_Detail_Info> subDetail = billDetail.ListDetail_Detail.ToList();
                foreach (Bill_Detail_Detail_Info detail in subDetail)
                {
                    DataRow rowSub = tableSubDetail.NewRow();
                    rowSub["DetailName"] = detail.DetailName;
                    rowSub["BillDetailId"] = billDetail.BillDetailId;
                    rowSub["Spec"] = detail.Spec;
                    rowSub["Num"] = detail.Num;
                    rowSub["UnitPrice"] = detail.UnitPrice;
                    if (IsNeedPrintMoney)
                    {
                        rowSub["Count"] = detail.Count;
                    }
                    else
                    {
                        rowSub["Count"] = 0;
                    }

                    rowSub["Area"] = detail.Area;
                    rowSub["Type"] = detail.Type;
                    tableSubDetail.Rows.Add(rowSub);
                }
            }

            tableDetail.TableName = "tableDetail";
            tableSubDetail.TableName = "tableSubDetail";
            #endregion

            #region 打印报表
            DataSet set = new DataSet("ds");
            set.Tables.Add(tableTitle);
            set.Tables.Add(tableDetail);
            set.Tables.Add(tableSubDetail);

            set.WriteXml(@"C:\Windows\xmldata\PrintTicket.xml", XmlWriteMode.WriteSchema);
            report.RegisterData(tableTitle, "tableTitle");
            report.RegisterData(tableDetail, "tableDetail");
            report.RegisterData(tableSubDetail, "tableSubDetail");
            report.Prepare();
            report.ShowPrepared();
            //report.Print();
            #endregion



        }

        /// <summary>
        /// 产品明细表
        /// </summary>
        /// <returns></returns>
        public DataTable CreatePrintDataTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("OrderBagId", typeof(int));
            table.Columns.Add("OrderProductId", typeof(int));
            table.Columns.Add("OrderProductCode", typeof(string));
            table.Columns.Add("BagCode", typeof(string));
            table.Columns.Add("BagName", typeof(string));
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("ProductName", typeof(string));
            table.Columns.Add("ProductCode", typeof(string));
            table.Columns.Add("ProductNum", typeof(int));
            table.Columns.Add("CreateTime", typeof(DateTime));
            table.Columns.Add("PreFetchTime", typeof(DateTime));
            table.Columns.Add("OutRemark", typeof(string));
            table.Columns.Add("FetchTime", typeof(DateTime));
            table.Columns.Add("FetchRemark", typeof(string));
            table.Columns.Add("CreateUserName", typeof(string));
            table.Columns.Add("Size", typeof(string));
            table.Columns.Add("PhotoNum", typeof(int));


            return table;
        }
        /// <summary>
        /// 商户信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopTop()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopId", typeof(int));
            table.Columns.Add("shopName", typeof(string));
            table.Columns.Add("shopKeeper", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("address", typeof(string));

            return table;

        }
        /// <summary>
        /// 为外商信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateOutShopTop()
        {
            DataTable table = new DataTable();
            table.Columns.Add("OutShopId", typeof(int));
            table.Columns.Add("OutShopName", typeof(string));
            table.Columns.Add("Keeper", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("City", typeof(string));
            table.Columns.Add("Addr", typeof(string));
            table.Columns.Add("Code", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            table.Columns.Add("Type", typeof(bool));
            return table;

        }
        /// <summary>
        /// 创建title表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillTitle()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("ShopId", typeof(int));
            table.Columns.Add("BillOrderCode", typeof(string));
            table.Columns.Add("shopKeeper", typeof(string));
            table.Columns.Add("QQ", typeof(string));
            table.Columns.Add("BillId", typeof(string));
            table.Columns.Add("CreateTime", typeof(DateTime));
            table.Columns.Add("Balance", typeof(double));
            table.Columns.Add("BillCount", typeof(double));
            table.Columns.Add("CreditLevel", typeof(int));
            table.Columns.Add("Salesman", typeof(string));
            table.Columns.Add("BillIndex", typeof(string));
            table.Columns.Add("CheckOutType", typeof(string));
            return table;

        }
        /// <summary>
        /// 创建明细产品
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("OrderInfoCode", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            table.Columns.Add("OrderBagName", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建明细收费项目表
        /// 
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillSubDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("DetailName", typeof(string));
            table.Columns.Add("Spec", typeof(string));
            table.Columns.Add("Num", typeof(int));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("Count", typeof(double));
            table.Columns.Add("Area", typeof(double));
            table.Columns.Add("Type", typeof(int));
            return table;
        }
        /// <summary>
        /// 创建发货信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateFahuoTable()
        {
            DataTable table = new DataTable("tableBottom");
            table.Columns.Add("ConsigneeName", typeof(string));
            table.Columns.Add("ConsigneeTelePhone", typeof(string));
            table.Columns.Add("DistributionAddress", typeof(string));
            table.Columns.Add("BusTimetable", typeof(string));//收货单位
            table.Columns.Add("ReMark", typeof(string));
            table.Columns.Add("DistributionMode", typeof(string));
            table.Columns.Add("Fahuodanwei", typeof(string));
            table.Columns.Add("Fahuodianhua", typeof(string));

            return table;
        }

        internal int GetProductNum(int instyle)
        {
            return _bll.GetProductNum(instyle);
        }
    }
}
